package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    /**
     *  1. <T extends BaseEnum>   T是BaseEnum 子类
     *  2. Converter<String, T>   将String类型转化为具体的T
     *     例子:  labelList(@RequestParam(required = false) ItemType type)   T 就是ItemType
     */

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //1.转化数据类型
                int code = Integer.valueOf(source);
                //2.获取当前springmvc中接收参数的所有枚举类型的数据
                //  APARTMENT(1, "公寓"),ROOM(2, "房间");
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    if(enumConstant.getCode() == code){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法的枚举值:" + source);
            }
        };
    }
}
